package com.avantis.admin.config.shiro;

import com.avantis.admin.service.AdminUserService;
import com.avantis.admin.service.PermissionService;
import com.avantis.admin.utils.PasswordHelper;
import com.avantis.common.entity.AdminUser;
import com.avantis.common.entity.Permission;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class YaphetsRealm extends AuthorizingRealm {

    private static final Logger LOGGER= LoggerFactory.getLogger(YaphetsRealm.class);


    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    protected StringRedisTemplate writeTemplate;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) throws AuthenticationException {
        Integer id = (Integer) principals.getPrimaryPrincipal();

        List<Permission> permissionList = permissionService.loadUserPermission(id);

        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        permissionList.forEach(p->info.addStringPermission(p.getPerUrl()));
        return info;
    }

    /**
     * 注入数据源进比较
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token = (JwtToken) authenticationToken;

        String password = PasswordHelper.encryptPassword(authenticationToken.getPrincipal().toString(), token.getCredentials().toString());
        //获取用户的输入的账号.
        AdminUser user = adminUserService.login(authenticationToken.getPrincipal().toString(), password);
        if(user==null) throw new IncorrectCredentialsException("用户名或密码不正确!");
        if (0==user.getEnable()) {
            throw new LockedAccountException(); // 帐号锁定
        }


        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
